﻿using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Diagnostics;
using Microsoft.SharePoint.BusinessData.SharedService;
using Microsoft.BusinessData.MetadataModel;
using Microsoft.BusinessData.MetadataModel.Collections;
using Microsoft.BusinessData.Runtime;
using Microsoft.BusinessData.Infrastructure;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WorkflowActions;
using Microsoft.SharePoint.Administration;

namespace CreateBcsEntity
{
    public partial class CreateBcsEntityActivity : Activity
    {

        #region  Fields

        public static DependencyProperty __ContextProperty = DependencyProperty.Register("__Context", typeof(WorkflowContext), typeof(CreateBcsEntityActivity));
        public static DependencyProperty BcsEntityNameProperty = DependencyProperty.Register("BcsEntityName", typeof(string), typeof(CreateBcsEntityActivity));
        public static DependencyProperty BcsNameSpaceProperty = DependencyProperty.Register("BcsNameSpace", typeof(string), typeof(CreateBcsEntityActivity));
        public static DependencyProperty LobSystemInstanceProperty = DependencyProperty.Register("LobSystemInstance", typeof(string), typeof(CreateBcsEntityActivity));
        public static DependencyProperty BcsCreateMethodNameProperty = DependencyProperty.Register("BcsCreateMethodName", typeof(string), typeof(CreateBcsEntityActivity));
        public static DependencyProperty ItemPropertiesProperty = DependencyProperty.Register("ItemProperties", typeof(Hashtable), typeof(CreateBcsEntityActivity));
        public static DependencyProperty OverwriteProperty = DependencyProperty.Register("Overwrite", typeof(bool), typeof(CreateBcsEntityActivity));
        public static DependencyProperty ListIdProperty = DependencyProperty.Register("ListId", typeof(string), typeof(CreateBcsEntityActivity));

      //  public static DependencyProperty ImpersonationAccountProperty = DependencyProperty.Register("ImpersonationAccount", typeof(string), typeof(CreateBcsEntity));


        public static DependencyProperty NewItemIdProperty = DependencyProperty.Register("NewItemId", typeof(Microsoft.SharePoint.Workflow.SPItemKey), typeof(CreateBcsEntityActivity));
        #endregion

        #region Properties

        // Properties
        [ValidationOption(ValidationOption.Optional)]
        public WorkflowContext __Context
        {
            get
            {
                return (WorkflowContext)base.GetValue(__ContextProperty);
            }
            set
            {
                base.SetValue(__ContextProperty, value);
            }
        }

        [BrowsableAttribute(true)]
        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [ValidationOption(ValidationOption.Optional)]
        public Hashtable ItemProperties
        {
            get
            {
                return (Hashtable)base.GetValue(ItemPropertiesProperty);
            }
            set
            {
                base.SetValue(ItemPropertiesProperty, value);
            }
        }

        [ValidationOption(ValidationOption.Required)]
        public string ListId
        {
            get
            {
                return (string)base.GetValue(ListIdProperty);
            }
            set
            {
                base.SetValue(ListIdProperty, value);
            }
        }

        [ValidationOption(ValidationOption.Required)]
        public bool Overwrite
        {
            get
            {
                return (bool)base.GetValue(OverwriteProperty);
            }
            set
            {
                base.SetValue(OverwriteProperty, value);
            }
        }


        [BrowsableAttribute(true)]
        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [ValidationOption(ValidationOption.Optional)]
        public string BcsEntityName
        {
            get
            {
                return (string)base.GetValue(BcsEntityNameProperty);
            }
            set
            {
                base.SetValue(BcsEntityNameProperty, value);
            }
        }

        [BrowsableAttribute(true)]
        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [ValidationOption(ValidationOption.Optional)]
        public string BcsNameSpace
        {
            get
            {
                return (string)base.GetValue(BcsNameSpaceProperty);
            }
            set
            {
                base.SetValue(BcsNameSpaceProperty, value);
            }
        }

        [BrowsableAttribute(true)]
        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [ValidationOption(ValidationOption.Optional)]
        public string BcsCreateMethodName
        {
            get
            {
                return (string)base.GetValue(BcsCreateMethodNameProperty);
            }
            set
            {
                base.SetValue(BcsCreateMethodNameProperty, value);
            }
        }


        [BrowsableAttribute(true)]
        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [ValidationOption(ValidationOption.Optional)]
        public string LobSystemInstance
        {
            get
            {
                return (string)base.GetValue(LobSystemInstanceProperty);
            }
            set
            {
                base.SetValue(LobSystemInstanceProperty, value);
            }
        }

        /*
        [ValidationOption(ValidationOption.Required)]
        public string ImpersonationAccount
        {
            get
            {
                return (string)base.GetValue(ImpersonationAccountProperty);
            }
            set
            {
                base.SetValue(ImpersonationAccountProperty, value);
            }
        }
        */

        [BrowsableAttribute(true)]
        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [ValidationOption(ValidationOption.Optional)]
        public Microsoft.SharePoint.Workflow.SPItemKey NewItemId
        {
            get
            {
                return (Microsoft.SharePoint.Workflow.SPItemKey)base.GetValue(NewItemIdProperty);
            }
            set
            {
                base.SetValue(NewItemIdProperty, value);
            }
        }

        #endregion


        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)       
        {
            // Debug.Assert(false);
                SPWeb currentWeb = this.__Context.Web;           

                using (new SPServiceContextScope(SPServiceContext.GetContext(this.__Context.Site)))
                {
                    
                    BdcService service = SPFarm.Local.Services.GetValue<BdcService>(String.Empty);
                    IMetadataCatalog catalog = service.GetDatabaseBackedMetadataCatalog(SPServiceContext.Current);
                    IEntity entity = catalog.GetEntity(this.BcsNameSpace, this.BcsEntityName);
                    ILobSystem LobSystem = entity.GetLobSystem();
                    ILobSystemInstance LobSystemInstance = LobSystem.GetLobSystemInstances()[this.LobSystemInstance];

                    IMethodInstance method = entity.GetMethodInstance(this.BcsCreateMethodName, MethodInstanceType.Creator);

                    try
                    {
                        CreateBcsItem(entity, LobSystemInstance, method);
                    }
                    finally
                    {
                        if (LobSystemInstance != null)
                            LobSystemInstance.FlushConnections();
                    }
                }            

            return ActivityExecutionStatus.Closed;

        }


        private void CreateBcsItem(IEntity entity, ILobSystemInstance LobSystemInstance, IMethodInstance method)
        {
                
                     Hashtable itemProperties = this.ItemProperties; // Property values from SP Designer mapping 
                     IView createView = entity.GetCreatorView(this.BcsCreateMethodName);
                     IFieldValueDictionary fieldValueDictionary = createView.GetDefaultValues();

                     foreach (string ParamName in itemProperties.Keys)
                     {
                         fieldValueDictionary[ParamName] = itemProperties[ParamName];
                     }

                     Identity id = entity.Create(fieldValueDictionary, LobSystemInstance);
                     this.NewItemId = new Microsoft.SharePoint.Workflow.SPItemKey(id.Serialize());
                         

        }

     
    }
}
